<template>
  <div>
    <el-card>
      <div ref="kLineChart" style="width: 100%; height: 800px"></div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getKlineInfo } from "@/api/system/CsvData";
import { getTechnicalIndexData } from "@/api/system/TechnicalIndex";
const upColor = "#00da3c";
const downColor = "#ec0000";

export default {
  name: "Detail",
  created() {
    this.klineId = this.$route.query.id;
    this.type = this.$route.query.type;
  },
  data() {
    return {
      //k线图
      myChart: {},
      chartDom: {},
      option: {},
      data: [],
      klineId: 0,
      type: 0,
      // 模拟K线数据
      kLineData: {},
    };
  },
  mounted() {
    if (['1','2','3'].includes(this.type)) {
      this.renderKLineChart2();
    }else{
      this.renderKLineChart();
    }
    
  },

  methods: {
    splitData(rawData) {
      let categoryData = [];
      let values = [];
      let volumes = [];
      for (let i = 0; i < rawData.length; i++) {
        categoryData.push(rawData[i].splice(0, 1)[0]);
        values.push(rawData[i]);
        volumes.push([
          i,
          rawData[i][4],
          parseFloat(rawData[i][0]) > parseFloat(rawData[i][1]) ? 1 : -1,
        ]);
      }
      return {
        categoryData: categoryData,
        values: values,
        volumes: volumes,
      };
    },
    calculateMA(dayCount, data) {
      var result = [];
      for (var i = 0, len = data.values.length; i < len; i++) {
        if (i < dayCount) {
          result.push("-");
          continue;
        }
        var sum = 0.0;
        for (var j = 0; j < dayCount; j++) {
          sum += parseFloat(data.values[i - j][1]);
        }
        result.push(+(sum / dayCount).toFixed(2));
      }
      return result;
    },

    renderKLineChart() {
      //初始化k线图
      getKlineInfo(this.klineId).then((response) => {
        this.data = this.splitData(response.data.kLineDataList);
        let data = this.data;
        this.chartDom = this.$refs.kLineChart;
        this.myChart = echarts.init(this.chartDom, "dark");
        this.option = {
          animation: false,
          legend: {
            bottom: 10,
            left: "center",
            data: ["K线", "MA5", "MA10", "MA20", "MA30"],
          },
          // 图表标题配置
          title: {
            text: response.data.klineName + "(" + response.data.klineCode + ")",
          },
          tooltip: {
            trigger: "axis",
            axisPointer: {
              type: "cross",
            },
            borderWidth: 1,
            borderColor: "#ccc",
            padding: 10,
            textStyle: {
              color: "#000",
            },
            position: function (pos, params, el, elRect, size) {
              const obj = {
                top: 10,
              };
              obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]] = 30;
              return obj;
            },
            // extraCssText: 'width: 170px'
          },
          axisPointer: {
            link: [
              {
                xAxisIndex: "all",
              },
            ],
            label: {
              backgroundColor: "#777",
            },
          },
          toolbox: {
            feature: {
              dataZoom: {
                yAxisIndex: false,
              },
              brush: {
                type: ["lineX", "clear"],
              },
            },
          },
          brush: {
            xAxisIndex: "all",
            brushLink: "all",
            outOfBrush: {
              colorAlpha: 0.1,
            },
          },
          visualMap: {
            show: true,
            seriesIndex: 5,
            dimension: 2,
            pieces: [
              {
                label: "跌",
                value: 1,
                color: downColor,
              },
              {
                label: "涨",
                value: -1,
                color: upColor,
              },
            ],
          },
          grid: [
            {
              left: "10%",
              right: "8%",
              height: "50%",
            },
            {
              left: "10%",
              right: "8%",
              top: "63%",
              height: "16%",
            },
          ],
          xAxis: [
            {
              type: "category",
              data: data.categoryData,
              boundaryGap: false,
              axisLine: { onZero: false },
              splitLine: { show: false },
              min: "dataMin",
              max: "dataMax",
              axisPointer: {
                z: 100,
              },
            },
            {
              type: "category",
              gridIndex: 1,
              data: data.categoryData,
              boundaryGap: false,
              axisLine: { onZero: false },
              axisTick: { show: false },
              splitLine: { show: false },
              axisLabel: { show: false },
              min: "dataMin",
              max: "dataMax",
            },
          ],
          yAxis: [
            {
              scale: true,
              splitArea: {
                show: true,
              },
            },
            {
              scale: true,
              gridIndex: 1,
              splitNumber: 2,
              axisLabel: { show: false },
              axisLine: { show: false },
              axisTick: { show: false },
              splitLine: { show: false },
            },
          ],
          dataZoom: [
            {
              type: "inside",
              xAxisIndex: [0, 1],
              start: 0,
              end: 100,
            },
            {
              show: true,
              xAxisIndex: [0, 1],
              type: "slider",
              top: "85%",
              start: 0,
              end: 100,
            },
          ],
          series: [
            {
              name: "K线",
              type: "candlestick",
              data: data.values,
              itemStyle: {
                color: upColor,
                color0: downColor,
                borderColor: undefined,
                borderColor0: undefined,
              },
              markPoint: {
                label: {
                  formatter: function (param) {
                    return param != null ? Math.round(param.value) + "" : "";
                  },
                },
                data: [
                  // {
                  //   name: "Mark",
                  //   coord: ["2013/5/31", 2300],
                  //   value: 2300,
                  //   itemStyle: {
                  //     color: "rgb(41,60,85)",
                  //   },
                  // },
                  {
                    name: "highest value",
                    type: "max",
                    valueDim: "highest",
                    itemStyle: {
                      color: "blue",
                    },
                  },
                  {
                    name: "lowest value",
                    type: "min",
                    valueDim: "lowest",
                    itemStyle: {
                      color: "yellow",
                    },
                  },
                  {
                    name: "average value on close",
                    type: "average",
                    valueDim: "close",
                    itemStyle: {
                      color: "orange",
                    },
                  },
                ],
                tooltip: {
                  formatter: function (param) {
                    return param.name + "<br>" + (param.data.coord || "");
                  },
                },
              },
              markLine: {
                symbol: ["none", "none"],
                data: [
                  [
                    {
                      name: "from lowest to highest",
                      type: "min",
                      valueDim: "lowest",
                      symbol: "circle",
                      symbolSize: 10,
                      label: {
                        show: false,
                      },
                      emphasis: {
                        label: {
                          show: false,
                        },
                      },
                    },
                    {
                      type: "max",
                      valueDim: "highest",
                      symbol: "circle",
                      symbolSize: 10,
                      label: {
                        show: false,
                      },
                      emphasis: {
                        label: {
                          show: false,
                        },
                      },
                    },
                  ],
                  {
                    name: "min line on close",
                    type: "min",
                    valueDim: "close",
                  },
                  {
                    name: "max line on close",
                    type: "max",
                    valueDim: "close",
                  },
                ],
              },
            },
            {
              name: "MA5",
              type: "line",
              data: this.calculateMA(5, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA10",
              type: "line",
              data: this.calculateMA(10, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA20",
              type: "line",
              data: this.calculateMA(20, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "MA30",
              type: "line",
              data: this.calculateMA(30, data),
              smooth: true,
              lineStyle: {
                opacity: 0.5,
              },
            },
            {
              name: "Volume",
              type: "bar",
              xAxisIndex: 1,
              yAxisIndex: 1,
              data: data.volumes,
            },
          ],
        };

        this.myChart.setOption(this.option, true);
        this.myChart.on("dblclick", (params) => {
          if (params.componentType === "series") {
            const dataIndex = params.dataIndex;
            const klineData = this.data.values[dataIndex];
            console.log(
              "您点击了第" + dataIndex + "根K线，数据为：",
              klineData
            );
            // 进行其他标注操作，比如弹出提示框、在图表上标注等
          }
        });
      });
    },
    renderKLineChart2() {
      //初始化k线图
      getTechnicalIndexData({ klineId: this.klineId, type: this.type }).then(
        (response) => {
          this.data = this.splitData(response.data.kLineDataList);
          let data = this.data;
          this.chartDom = this.$refs.kLineChart;
          this.myChart = echarts.init(this.chartDom, "dark");
          this.option = {
            animation: false,
            legend: {
              bottom: 10,
              left: "center",
              data: ["K线", "MA5", "MA10", "MA20", "MA30"],
            },
            // 图表标题配置
            title: {
              text:
                response.data.klineName + "(" + response.data.klineCode + ")",
            },
            tooltip: {
              trigger: "axis",
              axisPointer: {
                type: "cross",
              },
              borderWidth: 1,
              borderColor: "#ccc",
              padding: 10,
              textStyle: {
                color: "#000",
              },
              position: function (pos, params, el, elRect, size) {
                const obj = {
                  top: 10,
                };
                obj[["left", "right"][+(pos[0] < size.viewSize[0] / 2)]] = 30;
                return obj;
              },
              // extraCssText: 'width: 170px'
            },
            axisPointer: {
              link: [
                {
                  xAxisIndex: "all",
                },
              ],
              label: {
                backgroundColor: "#777",
              },
            },
            toolbox: {
              feature: {
                dataZoom: {
                  yAxisIndex: false,
                },
                brush: {
                  type: ["lineX", "clear"],
                },
              },
            },
            brush: {
              xAxisIndex: "all",
              brushLink: "all",
              outOfBrush: {
                colorAlpha: 0.1,
              },
            },
            visualMap: {
              show: true,
              seriesIndex: 5,
              dimension: 2,
              pieces: [
                {
                  label: "跌",
                  value: 1,
                  color: downColor,
                },
                {
                  label: "涨",
                  value: -1,
                  color: upColor,
                },
              ],
            },
            grid: [
              {
                left: "10%",
                right: "8%",
                height: "50%",
              },
              {
                left: "10%",
                right: "8%",
                top: "63%",
                height: "16%",
              },
            ],
            xAxis: [
              {
                type: "category",
                data: data.categoryData,
                boundaryGap: false,
                axisLine: { onZero: false },
                splitLine: { show: false },
                min: "dataMin",
                max: "dataMax",
                axisPointer: {
                  z: 100,
                },
              },
              {
                type: "category",
                gridIndex: 1,
                data: data.categoryData,
                boundaryGap: false,
                axisLine: { onZero: false },
                axisTick: { show: false },
                splitLine: { show: false },
                axisLabel: { show: false },
                min: "dataMin",
                max: "dataMax",
              },
            ],
            yAxis: [
              {
                scale: true,
                splitArea: {
                  show: true,
                },
              },
              {
                scale: true,
                gridIndex: 1,
                splitNumber: 2,
                axisLabel: { show: false },
                axisLine: { show: false },
                axisTick: { show: false },
                splitLine: { show: false },
              },
            ],
            dataZoom: [
              {
                type: "inside",
                xAxisIndex: [0, 1],
                start: 0,
                end: 100,
              },
              {
                show: true,
                xAxisIndex: [0, 1],
                type: "slider",
                top: "85%",
                start: 0,
                end: 100,
              },
            ],
            series: [
              {
                name: "K线",
                type: "candlestick",
                data: data.values,
                itemStyle: {
                  color: upColor,
                  color0: downColor,
                  borderColor: undefined,
                  borderColor0: undefined,
                },
                markPoint: {
                  label: {
                    formatter: function (param) {
                      return param != null ? Math.round(param.value) + "" : "";
                    },
                  },
                  data: [
                    // {
                    //   name: "Mark",
                    //   coord: ["2013/5/31", 2300],
                    //   value: 2300,
                    //   itemStyle: {
                    //     color: "rgb(41,60,85)",
                    //   },
                    // },
                    {
                      name: "highest value",
                      type: "max",
                      valueDim: "highest",
                      itemStyle: {
                        color: "blue",
                      },
                    },
                    {
                      name: "lowest value",
                      type: "min",
                      valueDim: "lowest",
                      itemStyle: {
                        color: "yellow",
                      },
                    },
                    {
                      name: "average value on close",
                      type: "average",
                      valueDim: "close",
                      itemStyle: {
                        color: "orange",
                      },
                    },
                  ],
                  tooltip: {
                    formatter: function (param) {
                      return param.name + "<br>" + (param.data.coord || "");
                    },
                  },
                },
                markLine: {
                  symbol: ["none", "none"],
                  data: [
                    [
                      {
                        name: "from lowest to highest",
                        type: "min",
                        valueDim: "lowest",
                        symbol: "circle",
                        symbolSize: 10,
                        label: {
                          show: false,
                        },
                        emphasis: {
                          label: {
                            show: false,
                          },
                        },
                      },
                      {
                        type: "max",
                        valueDim: "highest",
                        symbol: "circle",
                        symbolSize: 10,
                        label: {
                          show: false,
                        },
                        emphasis: {
                          label: {
                            show: false,
                          },
                        },
                      },
                    ],
                    {
                      name: "min line on close",
                      type: "min",
                      valueDim: "close",
                    },
                    {
                      name: "max line on close",
                      type: "max",
                      valueDim: "close",
                    },
                  ],
                },
              },
              {
                name: "MA5",
                type: "line",
                data: this.calculateMA(5, data),
                smooth: true,
                lineStyle: {
                  opacity: 0.5,
                },
              },
              {
                name: "MA10",
                type: "line",
                data: this.calculateMA(10, data),
                smooth: true,
                lineStyle: {
                  opacity: 0.5,
                },
              },
              {
                name: "MA20",
                type: "line",
                data: this.calculateMA(20, data),
                smooth: true,
                lineStyle: {
                  opacity: 0.5,
                },
              },
              {
                name: "MA30",
                type: "line",
                data: this.calculateMA(30, data),
                smooth: true,
                lineStyle: {
                  opacity: 0.5,
                },
              },
              {
                name: "Volume",
                type: "bar",
                xAxisIndex: 1,
                yAxisIndex: 1,
                data: data.volumes,
              },
            ],
          };

          this.myChart.setOption(this.option, true);
          this.myChart.on("dblclick", (params) => {
            if (params.componentType === "series") {
              const dataIndex = params.dataIndex;
              const klineData = this.data.values[dataIndex];
              console.log(
                "您点击了第" + dataIndex + "根K线，数据为：",
                klineData
              );
              // 进行其他标注操作，比如弹出提示框、在图表上标注等
            }
          });
        }
      );
    },
  },
};
</script>

<style scoped lang="scss">
</style>
